package org.saasplay.resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * 票据构建器
 * <p>
 * Ticket builder implements Tickets
 * The ticket used to build a trusted access service
 *
 * <p>
 * If the builder doesn't meet the requirements,
 * you can implement the ticket base interface yourself
 * to customize the builder more in line with the current business
 * </p>
 *
 * @author cuishifeng
 * @date 2020-01-17
 */
public class TicketsBuilder implements Tickets {


    /**
     * The ticket data is stored in a JSONObject
     */
    private JSONObject ticketsJSONObject = new JSONObject();


    /**
     * Construct tickets based on objects
     *
     * @param tickets
     */
    public void buildTickets(Object tickets) {
        setTickets((JSONObject) JSONObject.toJSON(tickets));
    }

    /**
     * Construct tickets based on JSON characters (ticketsJson)
     *
     * @param ticketsJson
     */
    public void buildTickets(String ticketsJson) {
        setTickets(JSON.parseObject(ticketsJson));
    }

    /**
     * Construct tickets based on JSON Map<String, Object> (ticketsMap)
     *
     * @param ticketsMap
     */
    public void buildTickets(Map<String, Object> ticketsMap) {
        ticketsMap.forEach((k, v) -> this.ticketsJSONObject.put(k, v));
    }

    public void addTicket(String field, Object value) {
        this.ticketsJSONObject.put(field, value);
    }

    public void removeTicket(String field) {
        this.ticketsJSONObject.remove(field);
    }

    @Override
    public <T> T getTickets(Class<T> clazz) {
        if (ticketsJSONObject == null || ticketsJSONObject.isEmpty()) {
            throw new RuntimeException("tickets must is not null or empty!");
        }
        return ticketsJSONObject.toJavaObject(clazz);
    }

    @Override
    public void setTickets(JSONObject jsonObject) {
        this.ticketsJSONObject = jsonObject;
    }
}
